package com.malbbmsomanager.management;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.malbbmsomanager.adapter.DM_BBM_List_Adapters;
import com.malbbmsomanager.adapter.DM_BBM_List_Expand_Helper;
import com.malbbmsomanager.retailmanagement.DM_BBM_Retailer_Info_Main_Tabs;
import com.malbbmsomanager.retailmanagement.DM_BBM_Retailer_Master;
import com.malbbmsomanagerdemo.DM_BBM_InvoiceMenu;
import com.malbbmsomanagerdemo.R;

import android.app.ActionBar;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FilterQueryProvider;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

public class DM_BBM_Item_Master extends Activity implements
		ActionBar.OnNavigationListener {
	private String DBNAME = "dminvoicemanagerbbm.db";
	private String TOWN_DETAILS = "fTown";
	private String ITEM_DEBTOR = "fDebtor";
	private String ITEMMASTER_SUM = "FItemsMasterSum";
	TextView txtHeading;
	SQLiteDatabase mydb;
	String itemMasterCode;
	EditText myFilterCustomerItems;
	private ActionBar actionBar;
	private DM_BBM_List_Adapters dbHelperCustomerItems;
	private SimpleCursorAdapter dataAdapterCusomerItems;

	public void btnBack(View view) {
		Intent myIntent = new Intent(view.getContext(),
				DM_BBM_InvoiceMenu.class);
		myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		myIntent.putExtra("TAGID", "SALES");
		startActivityForResult(myIntent, 0);
		finish();
	}

	public void DisplayItemsSumDetails(View view) {
		Button retailerDet = (Button) view;
		itemMasterCode = retailerDet.getText().toString();
		updateItemsMasterSum();

		Intent myIntent = new Intent(view.getContext(),
				DM_BBM_ItemsMaster_Main_Tabs.class);
		myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivityForResult(myIntent, 0);
		finish();

	}

	private void updateItemsMasterSum() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		try {
			ContentValues addItemsMasSum = new ContentValues();
			addItemsMasSum.put("ItemCode", itemMasterCode);
			addItemsMasSum.put("ItmSumaddDate", getCurrentTimeStringCustom()
					.toString());
			mydb.insert(ITEMMASTER_SUM, null, addItemsMasSum);
		} catch (Exception e) {
		}
		mydb.close();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dm_bbm_item_master);

		actionBar = getActionBar();

		// Hide the action bar title
		actionBar.setDisplayShowTitleEnabled(true);
		actionBar.setDisplayHomeAsUpEnabled(false);

		txtHeading = (TextView) findViewById(R.id.txtHeading);
		txtHeading.setText("Items Master");

		dbHelperCustomerItems = new DM_BBM_List_Adapters(this);
		dbHelperCustomerItems.open();
		myFilterCustomerItems = (EditText) findViewById(R.id.dminvfiltercustomeritems);

		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		mydb.execSQL("DROP TABLE IF EXISTS FItemsMasterSum");
		try {
			mydb.execSQL("create table if not exists "
					+ ITEMMASTER_SUM
					+ "(itmsum_id integer primary key autoincrement,ItemCode text not null,ItmSumaddDate text not null);");
		} catch (Exception e) {
		}
		mydb.close();
		DisplayItemsList();
	}

	/*
	 * private void DisplayItemsList() { // TODO Auto-generated method stub
	 * ListView lvtypedes = (ListView) findViewById(R.id.dmitemslistview); //
	 * create the grid item mapping String[] fromtrdes = new String[] {
	 * "coldes_1", "coldes_2", "coldes_3" }; int[] totrdes = new int[] {
	 * R.id.itemrawname, R.id.itemrawbrand, R.id.itemsrawsummary }; // prepare
	 * the list of all records List<HashMap<String, String>> fillMapstrdes = new
	 * ArrayList<HashMap<String, String>>();
	 * 
	 * SQLiteDatabase mydb; mydb = openOrCreateDatabase(DBNAME,
	 * Context.MODE_PRIVATE, null); Cursor curListItems = null; try { String
	 * query =
	 * "SELECT FI.ItemCode,FI.ItemName,FI.BrandCode,FB.BrandCode,FB.BrandName from FItems FI , FBrand FB Where FI.BrandCode = FB.BrandCode"
	 * ; //String query = "SELECT * FROM FItems"; curListItems =
	 * mydb.rawQuery(query, null); } catch (Exception e) { }
	 * 
	 * if (curListItems != null) { if (curListItems.getCount() > 0) { while
	 * (curListItems.moveToNext()) { String strItemName =
	 * curListItems.getString(1); String strItemCode =
	 * curListItems.getString(0); String strBrandCode =
	 * curListItems.getString(2); String strBrandName =
	 * curListItems.getString(4);
	 * 
	 * 
	 * String retailerDetSum = strDebCode + "/" + strDebName + "/" + strTownCode
	 * + "/" +strTownName;
	 * 
	 * 
	 * HashMap<String, String> maptrdes = new HashMap<String, String>();
	 * maptrdes.put("coldes_1", strItemName); maptrdes.put("coldes_2",
	 * strBrandName); maptrdes.put("coldes_3", strItemCode);
	 * fillMapstrdes.add(maptrdes);
	 * 
	 * } // fill in the grid_item layout SimpleAdapter adaptertrdes = new
	 * SimpleAdapter(this, fillMapstrdes, R.layout.dm_bbm_item_master_listraw,
	 * fromtrdes, totrdes); lvtypedes.setAdapter(adaptertrdes); } }
	 * curListItems.close(); mydb.close(); }
	 */

	private void DisplayItemsList() {
		// TODO Auto-generated method stub
		Cursor cursor = dbHelperCustomerItems.fetchAllItemsByOrder();

		String[] columns = new String[] { DM_BBM_List_Adapters.KEY_ITEMCODE,
				DM_BBM_List_Adapters.KEY_ITEMNAME,
				DM_BBM_List_Adapters.KEY_PACKSIZE,
				DM_BBM_List_Adapters.KEY_BRAND,
				DM_BBM_List_Adapters.KEY_ITEMCODE };

		String[] fromtrdes = new String[] { "coldes_1", "coldes_2", "coldes_3",
				"coldes_4", "coldes_5" };
		// the XML defined views which the data will be bound to
		int[] to = new int[] { R.id.itemrawcode, R.id.itemrawname,
				R.id.itemrawpacksize, R.id.itemrawbrand, R.id.itemsrawsummary };

		dataAdapterCusomerItems = new SimpleCursorAdapter(this,
				R.layout.dm_bbm_item_master_listraw, cursor, columns, to, 0);

		ListView listView = (ListView) findViewById(R.id.dmitemslistview);
		// Assign adapter to ListView
		listView.setAdapter(dataAdapterCusomerItems);

		myFilterCustomerItems.addTextChangedListener(new TextWatcher() {

			public void afterTextChanged(Editable s) {
			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				dataAdapterCusomerItems.getFilter().filter(s.toString());
			}
		});

		dataAdapterCusomerItems
				.setFilterQueryProvider(new FilterQueryProvider() {
					public Cursor runQuery(CharSequence constraint) {
						return dbHelperCustomerItems
								.fetchAllItemsByNameByOrder(constraint
										.toString());
					}
				});

	}

	private String getCurrentTimeStringCustom() {
		// 2013-10-04 00:00:00.000
		Date dateNow = new Date();
		Calendar c = Calendar.getInstance();
		SimpleDateFormat ddMMMyyFormat = new SimpleDateFormat("dd/MM/yyyy");
		String date_to_string = ddMMMyyFormat.format(dateNow);
		return date_to_string;
	}

	@Override
	public void onBackPressed() {
		// Do Here what ever you want do on back press;

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_search:
			// search action
			return true;
		case R.id.action_location_found:
			// location found
			LocationFound();
			return true;
		case R.id.action_refresh:
			// refresh
			/*
			 * refreshMenuItem = item; // load the data from server new
			 * SyncData().execute();
			 */
			return true;
		case R.id.action_help:
			// help action
			return true;
		case R.id.action_check_updates:
			// check for updates action
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	private void LocationFound() {
		// TODO Auto-generated method stub
		Intent i = new Intent(DM_BBM_Item_Master.this, DM_BBM_InvoiceMenu.class);
		i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(i);
		finish();
		return;
	}

	@Override
	public boolean onNavigationItemSelected(int itemPosition, long itemId) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main_actions, menu);
		return true;
	}

}
